package com.fly.demo;

import java.io.IOException;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * Spring在启动完成后执行方法
 * 
 * @author 00fly
 * @version [版本号, 2018-09-26]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Component
public class Startup implements ApplicationListener<ContextRefreshedEvent>
{
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @PostConstruct
    public void init()
    {
        try
        {
            log.info("########## @PostConstruct init ###########");
            Resource resource = new ClassPathResource("sql/init.sql");
            String text = IOUtils.toString(resource.getURL(), StandardCharsets.UTF_8.toString());
            Stream.of(text.split(";")).filter(StringUtils::isNotBlank).forEach(jdbcTemplate::execute);
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    /**
     * 事件回调
     * 
     * @param event
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event)
    {
        ApplicationContext applicationContext = event.getApplicationContext();
        log.info("★★★★★★★★ {}", applicationContext);
        
        // servlet context初始化完成
        if (applicationContext.getParent() != null && SystemUtils.IS_OS_WINDOWS)
        {
            try
            {
                log.info("now open Browser...");
                ServletContext servletContext = applicationContext.getBean(ServletContext.class);
                String ip = InetAddress.getLocalHost().getHostAddress();
                String url = "http://" + ip + ":8080" + servletContext.getContextPath();
                Runtime.getRuntime().exec("cmd /c start /min " + url);
                Runtime.getRuntime().exec("cmd /c start /min " + url + "/customer/");
                Runtime.getRuntime().exec("cmd /c start /min " + url + "/h2-console/");
            }
            catch (Exception e)
            {
                log.error(e.getMessage(), e);
            }
        }
    }
}
